/*
 * @Description:
 * @Author: william
 * @Date: 2025-07-22 09:40:56
 * @LastEditors: william
 * @LastEditTime: 2025-10-28 16:42:45
 */
import { deviceInfo, DeviceModel, DeviceStatus } from '@/interface/device.js'
import { scheduler } from '@/utils/scheduler.js'

export const useDeviceStore = defineStore(
  'device',
  () => {
    const allDeviceList = ref([])
    const bindDeviceList = ref([])
    const deviceModelList = ref([]) // 适用设备型号

    watch(
      () => bindDeviceList.value,
      async (nv, ov) => {
        console.log('bindDeviceList', nv, ov)
        if (nv.length) {
          const { code } = await g_api.user.apiCheckNetwork()
          if (code !== 200) return
          // 刷新修改记录的版本号和修改时间
          nv.forEach(item => {
            // const { data } = await g_api.user.apiGetSystemTime()
            const t = Date.now()
            if (t > item.updateTime + 1500) {
              item.updateTime = t
            }
          })

          // 获取设备变更的部分设备列表
          nv.filter(item => {
            return ov.find(list => {
              return item.sn === list.sn && item.status !== list.status
            })
          }).forEach(item => {
            // 上传设备最新状态（在线状态、运行状态）设备在线状态：0-离线、1-在线
            g_api.device.apiReportDeviceStatus({
              sn: item.sn,
              workStatus: item.status,
              onlineStatus: item.onlineStatus,
              showToast: false
            })
            // 上传设备位置
            // g_api.device.apiReportDeviceLocation({
            //   sn: item.sn,
            //   workStatus: item.status,
            //   onlineStatus: item.onlineStatus,
            //   showToast: false
            // })
          })
        }

        // if (nv.length) {
        //   const { code } = await g_api.user.apiCheckNetwork()
        //   if (code !== 200) return
        //   // 上报设备信息
        //   g_api.device.apiUploadDeviceInfo({
        //     deviceList: nv,
        //     showToast: false
        //   })
        //   // 获取设备变更的部分设备列表
        //   nv.filter(item => {
        //     return ov.find(list => {
        //       return item.sn === list.sn && item.status !== list.status
        //     })
        //   }).forEach(item => {
        //     // 上传设备状态（在线状态、运行状态）
        //     g_api.device.apiReportDeviceStatus({
        //       sn: item.sn,
        //       workStatus: item.status,
        //       onlineStatus: null,
        //       showToast: false
        //     })
        //   })
        // }
      },
      {
        deep: true
      }
    )

    const startDeviceBindScheduler = (time = 1000 * 10) => {
      // 增加设备绑定数据上传任务
      scheduler.schedule(
        '设备列表数据上传定时任务',
        async () => {
          console.log('执行绑定设备列表数据上传定时任务')
          const { code } = await g_api.user.apiCheckNetwork()
          if (code !== 200) return
          // 上报设备列表信息
          if (bindDeviceList.value.length > 0) {
            g_api.device.apiUploadDeviceInfo({
              deviceList: bindDeviceList.value,
              showToast: false
            })
          }
        },
        time
      ) // 每30分钟执行一次
    }
   

    /**
     * 通过SN号查询绑定的设备信息
     * @param {string} deviceSn SN号
     * @returns {deviceInfo} 设备信息，没有返回null
     */
    const getDeviceInfoFromBindListBySn = deviceSn => {
      console.log(bindDeviceList.value)
      if (!bindDeviceList.value?.length) return null

      // 首先在bindDeviceList中查找
      const foundDevice = bindDeviceList.value.find(
        device =>
          device.sn === deviceSn ||
          device.bindOil === deviceSn ||
          device.bindElectronic === deviceSn
      )
      if (foundDevice?.sn === deviceSn) {
        return foundDevice
      }
      // 如果在bindDeviceList中找到绑定关系，但在allDeviceList中查找实际设备
      if (foundDevice) {
        return allDeviceList.value.find(device => device.sn === deviceSn)
      }
      return null
    }

    /**
     * 通过SN号查询绑定的设备信息
     * @param {number} model 设备类型
     * @param {string} deviceSn SN号
     * @returns {deviceInfo} 设备信息，没有返回null
     */
    const getDeviceInfoFromBindList = (model, deviceSn) => {
      console.log(bindDeviceList.value)
      if (!bindDeviceList.value?.length) return null

      // 仅对特定设备型号进行处理
      const supportedModels = [
        DeviceModel.CookingMachine,
        DeviceModel.RangeHood,
        DeviceModel.ElectronicScale
      ]
      if (!supportedModels.includes(model)) return null

      return getDeviceInfoFromBindListBySn(deviceSn)
    }

    /**
     * 更新绑定的设备状态
     * @param {string} deviceSn SN号
     * @param {number} status 设备状态
     */
    const updateDeviceStatus = (deviceSn, status) => {
      console.log(bindDeviceList.value)
      if (!bindDeviceList.value?.length) return false

      const foundDevice = bindDeviceList.value.find(
        device => device.sn === deviceSn
      )
      if (!foundDevice) return false

      foundDevice.status = status
      return true
    }

    const updateDevicePeripheralRatio = (deviceSn, driverId, ratio) => {
      console.log(bindDeviceList.value)
      if (!bindDeviceList.value?.length) return false
      const foundDevice = bindDeviceList.value.find(
        device => device.sn === deviceSn
      )
      if (!foundDevice || !foundDevice.peripheralList?.length) return false
      const foundPeripheral = foundDevice.peripheralList.find(
        peripheral => peripheral.driverId === driverId
      )
      if (!foundPeripheral) return false
      foundPeripheral.ratio = ratio
      foundDevice.updateTime = Date.now()
      console.log('updateDevicePeripheralRatio success:', foundDevice, driverId, ratio)
      return true
    }

    const setDeviceModelList = _ => {
      return g_api.device
        .apiDeviceQueryModelList({
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            deviceModelList.value = data.map(item => ({
              value: item,
              label: item
            }))
          }
          return {
            code,
            data
          }
        })
    }

    return {
      allDeviceList,
      bindDeviceList,
      deviceModelList,
      getDeviceInfoFromBindList,
      getDeviceInfoFromBindListBySn,
      updateDeviceStatus,
      setDeviceModelList,
      updateDevicePeripheralRatio,
      startDeviceBindScheduler
    }
  },
  {
    // persist: true // 配置持久化
    persist: [
      {
        key: 'device-store', // 自定义存储键名
        // storage: localStorage, // 默认是 localStorage,可以改为 sessionStorage,可全局配置
        pick: ['allDeviceList', 'bindDeviceList']
      }
    ]
  }
)
export function useOutsideDeviceStore() {
  return useDeviceStore(g_store)
}
